package klk.shop.objects;

import java.util.ArrayList;

/**
 * 
 * @author lueder
 * 
 */
public abstract class SortedSqlList extends ArticleList {

	private ArrayList<Integer> sortedIds;

	protected int totalCount = 0;

	protected int offset;
	protected int limit;

	protected enum ORDER {
		ASC, DESC
	}

	protected String order = ORDER.ASC.toString();
	protected String language;
	private int pointer = 0;

	/**
	 * 
	 */
	public SortedSqlList(String language) {
		this(0, 15, ORDER.ASC.toString(), language);

	}

	public SortedSqlList(int offset, int limit, String order, String language) {
		sortedIds = new ArrayList<Integer>();
		this.language = Languages.contains(language);
		this.offset = offset;
		this.limit = limit;
		if (order.equals(ORDER.DESC.toString()))
			this.order = order;

	}
	
	public int getTotalCount() {
		return totalCount;
	}

	public int getOffset() {
		return offset;
	}

	public int getLimit() {
		return limit;
	}

	@Override
	protected void add(Article a) {
		super.add(a);
		if (!sortedIds.contains(a.getArticleId()))
			sortedIds.add(a.getArticleId());
	}

	@Override
	protected void remove(Article a) {
		super.remove(a);
		sortedIds.remove(a.getArticleId());
	}

	@Override
	public Article get(int index) {
		return super.get(sortedIds.get(index));
	}

	public boolean hasMoreElements() {
		if(pointer < sortedIds.size())
			return true;
		else
		{
			pointer = 0;
			return false;
		}
	}

	public Article nextElement() {
		pointer++;
		try{
			return get(pointer);
		}
		catch(IndexOutOfBoundsException e){
			pointer = 0;
			return null;
			
		}
	}

	@Override
	public String toHtml(String path) {
		String html = "";
		for(int i = 0; i<sortedIds.size(); i++) {
			html += articles.get(sortedIds.get(i)).toHtml(path);
		}
		return html;
	}

	protected abstract void fromSql();

	protected abstract void computeTotalCount(String sql);
}
